package com.unitd.app.sso.controller;

import com.unitd.frame.comm.utils.StringUtils;
import com.unitd.frame.comm.utils.http.HttpUtils;
import com.unitd.frame.springweb.controller.result.AjaxResult;
import com.unitd.frame.sso.annotation.Action;
import com.unitd.frame.sso.annotation.Login;
import com.unitd.frame.sso.common.config.SSOConfig;
import com.unitd.frame.sso.common.helper.SSOHelper;
import com.unitd.frame.sso.common.token.SSOToken;
import com.unitd.frame.sso.common.token.Token;
import com.unitd.frame.sso.web.waf.request.WafRequestWrapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController extends BaseController {

	/**
	 * 登录 (注解跳过权限验证)
	 */
	@Login(action = Action.Skip)
	@RequestMapping("/login")
	public String login(Model model) {
		String returnUrl = request.getParameter(SSOConfig.getInstance().getParamReturl());
		Token token = SSOHelper.getToken(request);
		if (token == null) {
			/* 正常登录 需要过滤sql及脚本注入 */
			WafRequestWrapper wr = new WafRequestWrapper(request);
			String name = wr.getParameter("userid");
			if (name != null && !"".equals(name)) {
				// 设置登录 Cookie; 最后一个参数 true 时添加 cookie 同时销毁当前 JSESSIONID 创建信任的 JSESSIONID
				SSOToken st = new SSOToken(request, "1000");
				SSOHelper.setSSOCookie(request, response, st, true);

				// 重定向到指定地址 returnUrl
				if (StringUtils.isEmpty(returnUrl)) {
					returnUrl = "/index.html";
				} else {
					returnUrl = HttpUtils.decodeURL(returnUrl);
				}
				return redirectTo(returnUrl);
			} else {
				if (StringUtils.isNotEmpty(returnUrl)) {
					model.addAttribute("ReturnURL", returnUrl);
				}
				return "login";
			}
		} else {
			if (StringUtils.isEmpty(returnUrl)) {
				returnUrl = "/index.html";
			}
			return redirectTo(returnUrl);
		}
	}

	@Login(action = Action.Skip)
	@RequestMapping("/test")
	@ResponseBody
	public AjaxResult getAll() {
		return new AjaxResult("哈哈哈哈哈哈");
	}
}